﻿using log4net;
using StoreProject.BLL.SettingBLL;
using StoreProject.BLL;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using StoreProject.DAL;
using StoreProject.Forms.SettingForms;
using StoreProject.Entity.SettingEntity;
using StoreProject.Entity;
using StoreProject.Enum;
using StoreProject.Forms.WorkingProcedure;
using System.Reflection;
using StoreProject.Entity.OtherEntity;
using StoreProject.OtherUtil;
using System.Drawing.Printing;

namespace StoreProject.Forms
{
    public partial class OrderQueryAndEditForm : Form
    {
        ILog _log = LogManager.GetLogger("OrderQueryAndEditForm");
        WorkingProcedureBLL workingProcedureBLL = new WorkingProcedureBLL();
        OrderBLL _orderBll = new OrderBLL();
        CustomerBLL customerBLL = new CustomerBLL();
        LineTypeBLL lineTypeBLL = new LineTypeBLL();
        OperatorBLL operatorBLL = new OperatorBLL();
        private OrderEntity orderEntity;
        private List<WorkingProcedureEntity> workingProcedureEntities;

        private Bitmap memoryImage;
        IniConfig iniConfig = new IniConfig("printer_config.ini");

        protected object _currentObj = null;
        public object CurrEntity
        {
            get { return _currentObj; }
            set { _currentObj = value; }
        }
        public OrderQueryAndEditForm(bool isadmin)
        {
            InitializeComponent();
            if (!isadmin)
            {
                this.修改ToolStripMenuItem.Visible = false;
                this.修改ToolStripMenuItem.Enabled = false;
                this.删除ToolStripMenuItem.Visible = false;
                this.删除ToolStripMenuItem.Enabled = false;
            }
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            Query();
        }

        private void OrderQueryAndEditForm_Load(object sender, EventArgs e)
        {
            try
            {
                dataGridView1.Columns[1].Width = 115;
                printDocument1.EndPrint += PrintDocument1_EndPrint;
                dataGridView1.AutoGenerateColumns = false;
                printDocument1.PrintPage += PrintDocument1_PrintPage;
                cmbProcessFlow.DisplayMember = "ProcessFlowName";
                cmbProcessFlow.ValueMember = "Id";
                cmbLineType.DisplayMember = "LineTypeName";
                cmbLineType.ValueMember = "LineTypeName";
                cmbCustomer.DisplayMember = "CustomerName";
                cmbCustomer.ValueMember = "CustomerName";
                cmbOperator.DisplayMember = "OperatorName";
                cmbOperator.ValueMember = "OperatorName";
                var list = _orderBll.GetList().OrderByDescending(x => x.OrderId).Take(100).ToList().Select(x => x.OrderId).ToArray();
                this.cmbOrderId.Items.AddRange(list);

                InitData();
                Query();
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }
        }

        private void PrintDocument1_EndPrint(object sender, PrintEventArgs e)
        {
            MessageBox.Show("打印已完成!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void PrintDocument1_PrintPage(object sender, PrintPageEventArgs e)
        {
            e.Graphics.DrawImage(memoryImage, 0, 0);
        }

        public void InitData()
        {
            this.dateTimeCreateTimeBegin.Value = DateTime.Now.AddDays(-30);

            //工序数据源配置
            List<ProcessFlow> list = new List<ProcessFlow>();
            list.Add(new ProcessFlow());
            var groupList = workingProcedureBLL.GetListEx().GroupBy(x => x.ProcessFlowId);
            foreach (var group in groupList)
            {
                ProcessFlow processFlow = new ProcessFlow();
                processFlow.Id = group.Key;
                string temp = "";
                foreach (var item in group.ToList().OrderBy(x => x.IndexNum))
                {
                    temp += (item.IndexName + "+");
                }
                if (!string.IsNullOrEmpty(temp))
                    temp = temp.Remove(temp.Length - 1, 1);
                processFlow.ProcessFlowName = temp;
                list.Add(processFlow);

            }
            cmbProcessFlow.DataSource = list;

            //客户数据源配置
            List<CustomerEntity> customerList = new List<CustomerEntity>();
            customerList.Add(new CustomerEntity());
            customerList.AddRange(customerBLL.GetList().ToList());
            cmbCustomer.DataSource = customerList;

            //线型数据源配置
            List<LineTypeEntity> linetypeList = new List<LineTypeEntity>();
            linetypeList.Add(new LineTypeEntity());
            linetypeList.AddRange(lineTypeBLL.GetList().ToList());
            cmbLineType.DataSource = linetypeList;

            //操作员数据源配置
            List<OperatorEntity> operatorList = new List<OperatorEntity>();
            operatorList.Add(new OperatorEntity());
            operatorList.AddRange(operatorBLL.GetList().ToList());
            cmbOperator.DataSource = operatorList;
        }

        public void Query()
        {
            string OrderId = cmbOrderId.Text;
            string Batch = txtBatch.Text;
            string Operator = cmbOperator.Text;
            string Customer = cmbCustomer.Text;
            string FinishedProductName = txtFinishedProductName.Text;
            string DomesticAndExportSales = cmbDomesticAndExportSales.Text;
            string LineType = cmbLineType.Text;
            string SemiFinishedProductName = txtSemiFinishedProductName.Text;
            string ProcessFlowId = "";
            var item = cmbProcessFlow.SelectedItem as ProcessFlow;
            if (item != null)
                ProcessFlowId = item.Id;
            DateTime dateTimeCreateTimeBegin = this.dateTimeCreateTimeBegin.Value;
            DateTime dateTimeCreateTimeEnd = this.dateTimeCreateTimeEnd.Value;
            var list = _orderBll.GetListByWhereEx(OrderId, Batch, Operator, Customer, FinishedProductName, DomesticAndExportSales, LineType, SemiFinishedProductName, ProcessFlowId, dateTimeCreateTimeBegin, dateTimeCreateTimeEnd).OrderByDescending(x => x.OrderId).ToList();
            foreach (var temp in list)
            {
                List<ProcessFlow> lists = new List<ProcessFlow>();
                string ProcessFlowName = "";
                var curList = workingProcedureBLL.GetListByStatus(temp.ProcessFlowId).OrderBy(x => x.IndexNum);
                foreach (var group in curList)
                {
                    ProcessFlowName += (group.IndexName + "+");
                }
                if (!string.IsNullOrEmpty(ProcessFlowName))
                    ProcessFlowName = ProcessFlowName.Remove(ProcessFlowName.Length - 1, 1);
                temp.ProcessFlowName = ProcessFlowName;
            }
            dataGridView1.DataSource = list;
        }
        private void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex >= 0)
                {
                    dataGridView1.ClearSelection();
                    dataGridView1.Rows[e.RowIndex].Selected = true;
                    dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    contextMenuStrip1.Show(MousePosition.X, MousePosition.Y);
                }
            }
        }

        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            DataGridView dgv = (DataGridView)sender;
            if (dgv.CurrentRow != null)
            {
                this._currentObj = dgv.CurrentRow.DataBoundItem;
            }
            else
            {
                this._currentObj = null;
            }
        }


        private void 修改ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OrderEntity orderEntity = this._currentObj as OrderEntity;
            if (CanUpdate() && !string.IsNullOrEmpty(orderEntity.Id))
            {
                UpdateOrderForm updateOrderForm = new UpdateOrderForm(FormState.UPDATE, orderEntity);
                updateOrderForm.TopMost = true;
                updateOrderForm.ShowDialog();
                updateOrderForm.BringToFront();
                this.Query();
            }
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OrderEntity orderEntity = this._currentObj as OrderEntity;
            if (CanUpdate() && !string.IsNullOrEmpty(orderEntity.Id))
            {
                if (MessageBox.Show("请确认是否删除", "是否删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    var res = _orderBll.Delete(orderEntity);
                    if (res)
                    {
                        MessageBox.Show("删除成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.Query();
                    }
                    else
                    {
                        MessageBox.Show("删除失败!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    this.Query();
                }
            }
        }
        private bool CanUpdate()
        {
            if (_currentObj == null)
                return false;
            return true;
        }

        private void 打印ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OrderEntity orderEntity = this._currentObj as OrderEntity;
            if (CanUpdate() && !string.IsNullOrEmpty(orderEntity.Id))
            {
                this.orderEntity = orderEntity;
                workingProcedureEntities = workingProcedureBLL.GetListByStatus(orderEntity.ProcessFlowId).OrderBy(x => x.IndexNum).ToList();
                Print();
            }
        }


        public void Print()
        {
            try
            {
                CaptureScreen();
                if (IsExist())
                {
                    PrintByIniParam();
                }
                else
                {
                    SetPrinter();
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.ToString());
            }
        }

        /// <summary>
        /// 根据ini配置文件打印
        /// </summary>
        public void PrintByIniParam()
        {
            printDocument1.DefaultPageSettings.Landscape = Convert.ToBoolean(iniConfig.Read("Landscape", "OrderPrinter"));
            printDocument1.DefaultPageSettings.Margins.Right = Convert.ToInt32(iniConfig.Read("Right", "OrderPrinter"));
            printDocument1.DefaultPageSettings.Margins.Left = Convert.ToInt32(iniConfig.Read("Left", "OrderPrinter"));
            printDocument1.DefaultPageSettings.Margins.Top = Convert.ToInt32(iniConfig.Read("Top", "OrderPrinter"));
            printDocument1.DefaultPageSettings.Margins.Bottom = Convert.ToInt32(iniConfig.Read("Bottom", "OrderPrinter"));
            printDocument1.PrinterSettings.PrinterName = iniConfig.Read("PrinterName", "OrderPrinter");

            printDocument1.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize(iniConfig.Read("PaperName", "OrderPrinter"), Convert.ToInt32(iniConfig.Read("Width", "OrderPrinter")), Convert.ToInt32(iniConfig.Read("Height", "OrderPrinter")));
            //printDocument1.DefaultPageSettings.PaperSize.PaperName = iniConfig.Read("PaperName", "OrderPrinter");
            //printDocument1.DefaultPageSettings.PaperSize.RawKind = Convert.ToInt32(iniConfig.Read("RawKind", "OrderPrinter"));
            //printDocument1.DefaultPageSettings.PaperSize.Width = Convert.ToInt32(iniConfig.Read("Width", "OrderPrinter"));
            //printDocument1.DefaultPageSettings.PaperSize.Height = Convert.ToInt32(iniConfig.Read("Height", "OrderPrinter"));

            printDocument1.Print();
        }
        public bool IsExist()
        {
            var flag = iniConfig.KeyExists("Landscape", "OrderPrinter");
            if (!flag)
                return false;
            flag = iniConfig.KeyExists("PrinterName", "OrderPrinter");
            if (!flag)
                return false;
            flag = iniConfig.KeyExists("Top", "OrderPrinter");
            if (!flag)
                return false;
            flag = iniConfig.KeyExists("Bottom", "OrderPrinter");
            if (!flag)
                return false;
            flag = iniConfig.KeyExists("Left", "OrderPrinter");
            if (!flag)
                return false;
            flag = iniConfig.KeyExists("Right", "OrderPrinter");
            if (!flag)
                return false;
            flag = iniConfig.KeyExists("PaperName", "OrderPrinter");
            if (!flag)
                return false;
            flag = iniConfig.KeyExists("RawKind", "OrderPrinter");
            if (!flag)
                return false;
            flag = iniConfig.KeyExists("Width", "OrderPrinter");
            if (!flag)
                return false;
            flag = iniConfig.KeyExists("Height", "OrderPrinter");
            if (!flag)
                return false;
            return true;
        }

        /// <summary>
        /// 设置打印机参数保存到INI文件，并打印一次
        /// </summary>
        public void SetPrinter()
        {
            PrinterSettingEntity printerSettingEntity = new PrinterSettingEntity();
            PageSetting pageSetting = new PageSetting();
            PrinterSetting printerSetting = new PrinterSetting();
            //先把中变变量设置到控件中
            PageSetupDialog pageSetupDialog1 = new PageSetupDialog();
            pageSetupDialog1.Document = printDocument1;
            pageSetupDialog1.AllowMargins = true;
            pageSetupDialog1.AllowOrientation = true;
            pageSetupDialog1.AllowPaper = true;
            pageSetupDialog1.AllowPrinter = true;
            pageSetupDialog1.ShowHelp = true;
            if (pageSetupDialog1.ShowDialog() == DialogResult.OK)
            {
                printDocument1.DefaultPageSettings = pageSetupDialog1.PageSettings;
                pageSetting.Landscape = printDocument1.DefaultPageSettings.Landscape;

                pageSetting.PaperSize = new Entity.OtherEntity.PaperSize();
                pageSetting.PaperSize.PaperName = printDocument1.DefaultPageSettings.PaperSize.PaperName;
                pageSetting.PaperSize.RawKind = printDocument1.DefaultPageSettings.PaperSize.RawKind;
                pageSetting.PaperSize.Width = printDocument1.DefaultPageSettings.PaperSize.Width;
                pageSetting.PaperSize.Height = printDocument1.DefaultPageSettings.PaperSize.Height;

                pageSetting.Margin = new Margin();
                pageSetting.Margin.Top = printDocument1.DefaultPageSettings.Margins.Top;
                pageSetting.Margin.Bottom = printDocument1.DefaultPageSettings.Margins.Bottom;
                pageSetting.Margin.Left = printDocument1.DefaultPageSettings.Margins.Left;
                pageSetting.Margin.Right = printDocument1.DefaultPageSettings.Margins.Right;
                //printDocument1.DefaultPageSettings.Margins;
                printerSettingEntity.pageSetting = pageSetting;
            }
            else
                return;

            PrintDialog print = new PrintDialog();
            print.Document = printDocument1;
            print.AllowCurrentPage = true;
            print.AllowPrintToFile = true;
            print.AllowSelection = true;
            print.AllowSomePages = true;
            print.ShowHelp = true;
            if (print.ShowDialog() == DialogResult.OK)
            {
                printDocument1.PrinterSettings = print.PrinterSettings;
                printerSetting.PrinterName = printDocument1.PrinterSettings.PrinterName;
                printerSettingEntity.printerSetting = printerSetting;
            }
            else
                return;
            iniConfig.Write("Landscape", printerSettingEntity.pageSetting.Landscape == true ? "True" : "False", "OrderPrinter");
            iniConfig.Write("Top", printerSettingEntity.pageSetting.Margin.Top.ToString(), "OrderPrinter");
            iniConfig.Write("Bottom", printerSettingEntity.pageSetting.Margin.Bottom.ToString(), "OrderPrinter");
            iniConfig.Write("Left", printerSettingEntity.pageSetting.Margin.Left.ToString(), "OrderPrinter");
            iniConfig.Write("Right", printerSettingEntity.pageSetting.Margin.Right.ToString(), "OrderPrinter");
            iniConfig.Write("PrinterName", printerSettingEntity.printerSetting.PrinterName, "OrderPrinter");

            iniConfig.Write("PaperName", printerSettingEntity.pageSetting.PaperSize.PaperName, "OrderPrinter");
            iniConfig.Write("RawKind", printerSettingEntity.pageSetting.PaperSize.RawKind.ToString(), "OrderPrinter");
            iniConfig.Write("Width", printerSettingEntity.pageSetting.PaperSize.Width.ToString(), "OrderPrinter");
            iniConfig.Write("Height", printerSettingEntity.pageSetting.PaperSize.Height.ToString(), "OrderPrinter");
            //打印的是中间变量
            printDocument1.Print();
        }
        private void CaptureScreen()
        {
            var form1 = new TestPrintForm(orderEntity, workingProcedureEntities);
            var createControl = form1.GetType().GetMethod("CreateControl",
                            BindingFlags.Instance | BindingFlags.NonPublic);
            createControl.Invoke(form1, new object[] { true });

            var bm = new Bitmap(form1.Width, form1.Height);
            form1.DrawToBitmap(bm, new Rectangle(0, 0, bm.Width, bm.Height));
            //bm.Save(@"d:\bm.bmp");
            memoryImage = bm;
        }

        private void printDocument1_PrintPage_1(object sender, PrintPageEventArgs e)
        {
            e.Graphics.DrawImage(memoryImage, 0, 0);
        }

        private void OrderQueryAndEditForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.printDocument1.Dispose();
            this.printDocument1 = null;
        }
    }
}
